package org.iartisan.thought.web.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * <p>
 * 邮件发送服务
 *
 * @author King
 * @since 2018/5/29
 */
@Service
public class EmailSupport {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发件邮箱
     */
    @Value("${spring.mail.username}")
    private String from;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 发送html 邮件
     *
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            logger.error("邮件发送异常", e);
        }
    }
}
